package com.station.search.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONValidator;
import com.google.common.collect.ImmutableMap;
import com.station.search.common.exception.BusinessException;
import com.station.search.common.exception.ExceptionCode;
import com.station.search.common.exception.HttpException;
import com.station.search.domain.dto.WxAuthCode2SessionDTO;

import java.util.Objects;

/**
 * @author: JT
 * @date: 2021/10/19
 * @Title: 微信Http请求处理工具
 */
public class WeixinHttpUtil {

    private static final String APP_ID = "wx4a9800a9c1b38d99";
    private static final String SECURITY_KEY = "b1d5040b84354cf7ea49b920320c0818";
    private static final String GRANT_TYPE = "authorization_code";

    private static final String URL_AUTH_CODE2SESSION = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 校验登录凭证
     * @param jsCode: wx.login 获取的Code码
     * @return
     */
    public static WxAuthCode2SessionDTO authCode2Session(String jsCode) {
        String responseStr = HttpUtil.get(URL_AUTH_CODE2SESSION, ImmutableMap.of(
                "appid", APP_ID,
                "secret", SECURITY_KEY,
                "js_code", jsCode,
                "grant_type", GRANT_TYPE
        ));
        boolean isJson = JSONValidator.from(responseStr).validate();
        if (!isJson) {
            throw new HttpException(ExceptionCode.ERROR, "微信登录凭证校验请求发送失败，失败信息[{}], 返回数据[{}]", "请求返回JSON格式错误", responseStr);
        }
        WxAuthCode2SessionDTO wxAuthCode2SessionDTO = JSON.parseObject(responseStr, WxAuthCode2SessionDTO.class);
        if (Objects.nonNull(wxAuthCode2SessionDTO.getErrCode())) {
            throw new BusinessException(ExceptionCode.ERROR, "微信登录凭证校验失败，失败信息：[微信错误编码: {}, 微信错误信息: {}]", wxAuthCode2SessionDTO.getErrCode(), wxAuthCode2SessionDTO.getErrMsg());
        }
        return wxAuthCode2SessionDTO;
    }

}
